package com.yao2san.sim.storage.client.core.downloader;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.model.COSObject;
import com.yao2san.sim.storage.client.config.TencentCosProperties;
import com.yao2san.sim.storage.client.core.enums.StorageType;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @author wxg
 **/
public class TencentCosDownloader extends AbstractDownloader {

    private final TencentCosProperties tencentCosProperties;
    private final COSClient client;

    public TencentCosDownloader(COSClient client, TencentCosProperties tencentCosProperties) {
        this.tencentCosProperties = tencentCosProperties;
        this.client = client;
    }

    @Override
    public void download(String object, OutputStream out) throws IOException {
        String bucket = tencentCosProperties.getBucket();
        COSObject cosObject = client.getObject(bucket, object);
        IOUtils.copy(cosObject.getObjectContent(), out);
        cosObject.close();
    }

    @Override
    public String url(String object) {
        return url(object, false);
    }

    @Override
    public String url(String object, boolean preSigned) {
        if (preSigned) {
            Date expiration = Date.from(LocalDateTime.now().plusMinutes(30).atZone(ZoneId.systemDefault()).toInstant());
            return client.generatePresignedUrl(tencentCosProperties.getBucket(), object, expiration, HttpMethodName.GET).toString();
        } else {
            return tencentCosProperties.getBucket() + "." + tencentCosProperties.getEndpoint() + "/" + object;
        }
    }

    @Override
    public String getName() {
        return StorageType.TENCENT_COS.name();
    }
}
